//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ruoyi.live.user.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.live.app.service.CacheService;
import com.ruoyi.live.app.service.VideoService;
import com.ruoyi.live.configuration.SessionInfo;
import com.ruoyi.live.base.domain.*;
import com.ruoyi.live.base.mapper.*;
import com.ruoyi.live.base.service.impl.LiveExamJudgeServiceImpl;
import com.ruoyi.live.register.utils.RegisterContant;
import com.ruoyi.live.tool.assistant.IProcessBean;
import com.ruoyi.live.tool.commons.ICommons;
import com.ruoyi.live.tool.commons.IConvert;
import com.ruoyi.live.tool.commons.IProcess;
import com.ruoyi.live.tool.utils.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@Service
public class DeployService {
    @Autowired
    LiveExamMapper examDao;
    @Autowired
    LiveServerMapper serverDao;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LiveExamTaskMapper examTaskDao;
    @Autowired
    LiveProductMapper productDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    SystemParamMapper paramDao;
    @Autowired
    CacheService cacheService;
    @Autowired
    UserMapper userDao;
    @Autowired
    LiveExamJudgeMapper judgeDao;
    @Autowired
    LiveExamJudgeServiceImpl examJudgeService;
    @Autowired
    LiveTaskUserChannelMapper channelMapper;
    @Autowired
    VideoService videoService;

    public DeployService() {
    }

    public ModelAndView index() {
        List<LiveExam> exams = this.examDao.selectList(new QueryWrapper((new LiveExam()).setExamType(2)));
        return (new ModelAndView("deploy/index")).addObject("exam", exams.get(0));
    }

    public List<LiveServer> listServers(HttpServletRequest request) {
        List<LiveServer> servers = this.serverDao.selectList((Wrapper)null);
        String url = "http://%s:%s/liveapp/index.html";
        Iterator var4 = servers.iterator();

        while(var4.hasNext()) {
            LiveServer server = (LiveServer)var4.next();

            try {
                this.restTemplate.getForObject(String.format(url, server.getServerIp(), server.getHttpPort() + ""), String.class, new Object[0]);
                server.setStatus(1);
            } catch (RestClientException var7) {
                server.setStatus(2);
            }
        }

        return servers;
    }

    public List<LiveExamTask> getTaskData(Long examId) {
        return this.examTaskDao.selectList((Wrapper)(new QueryWrapper((new LiveExamTask()).setExamId(examId))).orderByAsc("task_order"));
    }

    public List<LiveProduct> getProductList() {
        return this.productDao.selectList((Wrapper)null);
    }

    public Map<String, Integer> getExamUserDetail(Long examId) {
        Map<String, Integer> res = new HashMap();
        String sql = "select ifnull((select count(1) from user where user_type = 3 and class_id in (select a.class_id from live_exam_class a)),0) allCount,ifnull((select count(1) from live_exam_user where state = 3),0) endCount,ifnull((select count(1) from live_exam_user where state = 2),0) startCount,ifnull((select count(1) from live_task_user_channel where channel_type = 2 and (live_video_state = 1 or screen_video_state = 1)),0) errorCount from dual";
        List<Map<String, Object>> maps = this.jdbcTemplate.queryForList(sql);
        Map<String, Object> map = (Map)maps.get(0);
        res.put("allCount", IConvert.object2int(map.get("allCount")));
        res.put("startCount", IConvert.object2int(map.get("startCount")));
        res.put("endCount", IConvert.object2int(map.get("endCount")));
        res.put("errorCount", IConvert.object2int(map.get("errorCount")));
        return res;
    }

    public List<SystemParam> loadIndexUrl() {
        return this.paramDao.selectList((Wrapper)(new QueryWrapper((new SystemParam()).setParamName("淘宝推广"))).orderByAsc("param_des"));
    }

    public void editIndexUrl(Long id, String url) {
        if (!url.startsWith("http://")) {
            url = "http://" + url;
        }

        SystemParam param = (SystemParam)this.paramDao.selectById(id);
        this.paramDao.updateById(param.setParamValue(url));
        this.cacheService.clearParamCache(param.getParamCode());
    }

    public void addIndexUrl(String url) {
        Long count = this.paramDao.selectCount(new QueryWrapper((new SystemParam()).setParamName("淘宝推广"))) + 1;
        this.paramDao.insert((new SystemParam()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setState(1).setParamCode("TG_" + count).setParamValue("http://" + url).setParamName("淘宝推广").setParamDes(count + ""));
    }

    public void startCheck(Long examId) {
    }

    public void startOneServer(Long id, HttpServletRequest request) throws IOException, InterruptedException {
        LiveServer server = (LiveServer)this.serverDao.selectById(id);
        String relativePath = server.getFilePath().replaceAll("webapps/live/record/", "");
        String startFile = request.getSession().getServletContext().getRealPath(relativePath) + "start.bat";

        try {
            Process child = Runtime.getRuntime().exec("cmd /c start " + startFile);

            try {
                child.waitFor();
            } catch (Exception var8) {
                throw var8;
            }
        } catch (Exception var9) {
            throw var9;
        }
    }

    // TODO:
    public Message backup(HttpServletRequest request, HttpServletResponse response) {
//        String toolPath = request.getSession().getServletContext().getRealPath("/static/static/plugin/") + "mysqldump.exe";
//        String fileName = System.currentTimeMillis() + ".sql";
//        String filePath = request.getSession().getServletContext().getRealPath("/static/static/data/sql/") + fileName;
//        StringBuilder cmdStr = new StringBuilder();
//        cmdStr.append("cmd.exe /c").append(" ").append(toolPath).append(" -u").append(RegisterContant.dataBaseUsername).append(" -p").append(RegisterContant.dataBasePassword).append(" -h").append("127.0.0.1").append(" -P").append(RegisterContant.dataBasePort).append(" ").append(DataSourceHelper.dataBaseName).append(" > ").append(filePath);
//        System.out.println(cmdStr);
//
//        try {
//            IProcessBean iProcessBean = IProcess.execProcess(cmdStr.toString(), true);
//            return new Message(true, fileName);
//        } catch (Exception var8) {
//            var8.printStackTrace();
//            return new Message(false, "备份失败");
//        }
        return null;
    }

    public void checkMode(Long userId) {
        User user = (User)this.userDao.selectById(userId);
        this.userDao.updateById((new User()).setId(userId).setOpenId("noneed".equals(user.getOpenId()) ? "need" : "noneed"));
    }

    public void doInertJudgeEmpty(Long userId, Long examId) {
        Long count = this.judgeDao.selectCount(new QueryWrapper((new LiveExamJudge()).setUserPlayerId(userId)));
        if (count == 0l) {
            User createUser = (User)this.userDao.selectById(userId);
            List<User> experts = this.userDao.selectList((new QueryWrapper((new User()).setUserSchool(createUser.getClassId()))).select(new String[]{"id", "user_login_name"}));
            List<LiveExamJudge> judges = new ArrayList();
            Iterator var7 = experts.iterator();

            while(var7.hasNext()) {
                User user = (User)var7.next();
                judges.add((new LiveExamJudge()).setExamId(examId).setUserJudgeId(user.getId()).setUserPlayerId(createUser.getId()).setGroupNo(1).setUserJudgeName(user.getUserLoginName()).setUserPlayerName(createUser.getUserLoginName()).setState(1));
            }

            this.examJudgeService.saveBatch(judges);
        }

    }

    public void uploadFile(Long id, MultipartFile file, HttpServletRequest request) throws Exception {
        Integer uploadState = 2;
        LiveTaskUserChannel channel = (LiveTaskUserChannel)this.channelMapper.selectById(id);
        String fileName = file.getOriginalFilename();
        if (ICommons.isNullOrEmpty(fileName)) {
            throw new Exception("文件名不能为空");
        } else {
            if (fileName.indexOf("\\") != -1) {
                fileName = fileName.substring(fileName.lastIndexOf("\\"));
            }

            String ext = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            if (ICommons.isNullOrEmpty(ext)) {
                throw new Exception("扩展名不能为空");
            } else if (!".mp4".contains(ext)) {
                throw new Exception("请上传.mp4文件");
            } else {
                String filePath = request.getServletContext().getRealPath("/static/static/data/record/");
                File targetFile = new File(filePath);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }

                FileOutputStream out = null;

                try {
                    out = new FileOutputStream(filePath + channel.getChannelName() + ".mp4");
                    out.write(file.getBytes());
                    uploadState = this.videoService.getScreenVideoInfo(id, request.getSession().getServletContext().getRealPath(""), channel.getChannelName());
                    this.channelMapper.updateById((new LiveTaskUserChannel()).setId(id).setUploadState(uploadState));
                } catch (Exception var19) {
                    var19.printStackTrace();
                    throw new Exception("上传失败");
                } finally {
                    try {
                        out.flush();
                        out.close();
                    } catch (Exception var18) {
                        var18.printStackTrace();
                    }

                }

            }
        }
    }
}
